package com.jeeplus.test.jlnu.admissionInfo.service.impl;

import com.alibaba.fastjson.JSON;
import com.jeeplus.test.education.domain.vo.EducationInfoVo;
import com.jeeplus.test.education.mapper.EducationInfoMapper;
import com.jeeplus.test.jlnu.admissionInfo.domain.entity.AdmissionInfo;
import com.jeeplus.test.jlnu.admissionInfo.domain.entity.ImportFailLog;
import com.jeeplus.test.jlnu.admissionInfo.mapper.AdmissionInfoMapper;
import com.jeeplus.test.jlnu.admissionInfo.mapper.ExcelMapper;
import com.jeeplus.test.jlnu.admissionInfo.service.AdmissionInfoService;
import com.jeeplus.test.jlnu.admissionInfo.service.ContinueService;
import com.jeeplus.test.jlnu.admissionInfo.utils.MyWebSocketHandler;
import com.jeeplus.test.jlnu.admissionInfo.utils.VerifyExcel;
import com.jeeplus.test.jlnu.archivalInfo.domain.entity.ArchivalInfo;
import com.jeeplus.test.jlnu.changeStuInfo.domain.entity.ChangeStuInfo;
import com.jeeplus.test.jlnu.changeStuInfo.mapper.ChangeStuInfoMapper;
import com.jeeplus.test.jlnu.deanOffice.domain.entity.JlnuDeansOffice;
import com.jeeplus.test.jlnu.graduationInfo.domain.entity.NewGraduationInfo;
import com.jeeplus.test.jlnu.student.domain.entity.BsssStudentInfo;
import com.jeeplus.test.jlnu.xlsxManage.service.JlnuXlsxManageService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class ContinueServiceImpl implements ContinueService {
    @Autowired
    private ExcelMapper excelMapper;

    @Autowired
    private EducationInfoMapper educationInfoMapper;

    @Autowired
    private MyWebSocketHandler webSocketHandler;

    @Autowired
    private ChangeStuInfoMapper changeStuInfoMapper;

    @Autowired
    private AdmissionInfoMapper admissionInfoMapper;

    @Resource
    private JlnuXlsxManageService jlnuXlsxManageService;

    @Autowired
    private AdmissionInfoService admissionInfoService;

    @Override
    public void insertDataStu(List<EducationInfoVo> dataList,String importType,String officeId,String templateInfoType,int templateId) {

        try {
            if (CollectionUtils.isEmpty(dataList)) {
                return;

            }
            //需要导入的数据集合
            List<EducationInfoVo> newDataList = new ArrayList<>();

            //判断Excel中是否有重复的数据
            Map repeatParam = new HashMap();

            //错误数据集合
            List<String> errorList = new ArrayList();
            //查模板库对应数据（入参加id）
            List<Map<String, Object>> finalContent = VerifyExcel.getTemplateContent(jlnuXlsxManageService,  templateId);

            AtomicInteger i = new AtomicInteger();
            dataList.forEach(e -> {

                i.getAndIncrement();
                VerifyExcel.validateObjectFields(e, finalContent, errorList,i);

                //VerifyExcel.validateObjectFields(e, finalContent, errorList);
                String type = null;
                String suffix = null;

                if (!StringUtils.isEmpty(e.getStudentId())) {
                    type = "xh";
                    suffix = e.getStudentId();
                } else if (!StringUtils.isEmpty(e.getZkzh())) {
                    e.setStudentId(e.getZkzh());
                    type = "zkzh";
                    suffix = e.getZkzh();
                } else if (!StringUtils.isEmpty(e.getKsh())) {
                    e.setStudentId(e.getKsh());
                    type = "ksh";
                    suffix = e.getKsh();
                }


                if (StringUtils.isEmpty(suffix)) {
                    //学号、准考证号都为空则不可导入
                    String msg = "第"+i+"行 " + " 姓名：" + e.getXm() + "学号为空";
                    errorList.add(msg);
                    return;
                }

                if(!errorList.isEmpty()){
                    return;
                }


                if (suffix != null) {
                    repeatParam.put("XH" + suffix, System.currentTimeMillis());
                    //如果是通过数据管理中导入的Excel数据就只覆盖重复的jlnu_deans_office主表数据
                    if (importType.equals("DBMS")) {
                        List<Integer> ids = educationInfoMapper.selectAdmissionInfo(type, suffix);


                        if (!CollectionUtils.isEmpty(ids)) {
                            AdmissionInfo admissionInfo = new AdmissionInfo();
                            admissionInfo.setGradation(e.getLqcc());//层次
                            admissionInfo.setYear(e.getLgnf()); //年度
                            admissionInfo.setOfficeId(e.getOfficeId());
                            admissionInfo.setStudentId(e.getStudentId());
                            admissionInfo.setAdmissionNum(e.getZkzh());//准考证号
                            admissionInfo.setName(e.getXm());//姓名
                            admissionInfo.setGender(e.getXb());//性别
                            admissionInfo.setTransferState(1);

                            // 将字符串转换为 Date 对象
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                            try {
                                Date birthDate = sdf.parse(e.getCsrq());
                                admissionInfo.setBirthday(birthDate);//出生日期
                            } catch (ParseException error) {
                                System.out.println(error.getMessage());
                            }

                            admissionInfo.setPoliticalOutlook(e.getZzmm());//政治面貌
                            admissionInfo.setNation(e.getMz());//民族
                            admissionInfo.setIdCard(e.getSfzh());//身份证号
                            admissionInfo.setAdmissionMajor(e.getMajorName());//专业

                            // 设置录取学校为吉林师范大学
                            admissionInfo.setAdmissionSchools("吉林师范大学");//录取学校
                            admissionInfo.setAdmissionTime(e.getAdmissionDate());//录取时间
                            admissionInfo.setEducationalSystem(e.getXz());//学制
                            admissionInfo.setInfoSource("研究生招生数据");
                            admissionInfo.setFlag(BsssStudentInfo.EDUCATION);
                            admissionInfoMapper.batchUpdateeAdmissionInfoById(ids, admissionInfo);
                        } else {
                            newDataList.add(e);
                        }
                    } else {
                        //如果是通过录取管理中导入的Excel数据就只覆盖重复的jlnu_education_info主表数据
                        List<Integer> ids = educationInfoMapper.selectEducationInfo(type, suffix);
                        if (!CollectionUtils.isEmpty(ids)) {
                            //数据库中有相同的数据则覆盖
                            educationInfoMapper.batchUpdateEducationInfo(ids, e);
                        } else {
                            newDataList.add(e);
                        }
                    }
                }
            });

            if(!CollectionUtils.isEmpty(errorList)){
                sendMsg(errorList);

                //存储到数据库
                ImportFailLog param = new ImportFailLog();
                param.setTemplateId(templateId);
                param.setMessage(JSON.toJSONString(errorList));
                param.setImportType("1");
                admissionInfoService.importLogAdd(param);
            }

            if (!CollectionUtils.isEmpty(newDataList)) {

                List<AdmissionInfo> admissionInfos = copyAdmissionInfos(newDataList,importType);
                List<NewGraduationInfo> graduationInfos = copyGraduationInfos(newDataList,importType);
                List<ArchivalInfo> archivalInfos = copyArchivalInfoInfos(newDataList,importType);
                List<ChangeStuInfo> changeStuInfos = dataList.stream()
                        .map(e -> {
                            ChangeStuInfo csi = new ChangeStuInfo();
                            csi.setStudentId(e.getStudentId());
                            csi.setOfficeId(e.getOfficeId());
                            csi.setSource("2");
                            csi.setCreateTime(new Date());
                            csi.setKsh(e.getKsh());
                            csi.setName(e.getXm());
                            csi.setGender(e.getXb());
                            csi.setMajorName(e.getLqzy());
                            csi.setApproveState(0);
                            csi.setYear(e.getLgnf());
                            csi.setExamTicketNumber(e.getZkzh());
                            csi.setBirthDate(e.getCsrq());
                            csi.setEthnicity(e.getMz());
                            csi.setPoliticalStatus(e.getZzmm());
                            csi.setIdCardNumber(e.getSfzh());
                            csi.setAcademicSystem(e.getXz());
                            csi.setAreaCode(e.getSyssdm());
                            csi.setExamTicketNumber(e.getZkzh());
                            csi.setEducationLevel(e.getLqcc());
                            csi.setStudyForm(e.getXxxs());
                            csi.setMajorCode(e.getZydm());
                            csi.setAreaCode(e.getYzbm());

                            return csi; // 返回生成的 AdmissionInfo 对象
                        }).collect(Collectors.toList());// 收集到 admissionInfos 列表中

                changeStuInfoMapper.insertChangeStu(changeStuInfos);//学籍管理循环插入
                educationInfoMapper.insertEducationInfo(newDataList);
                // 插入录取信息表全部数据
                excelMapper.saveFirstData(admissionInfos);
//                // 插入学籍信息表（只插入学号）
//                excelMapper.saveSecondData(admissionInfos);
//                // 插入毕业信息表（只插入学号）
//                excelMapper.saveThirdData(graduationInfos);
//                // 插入就业信息表（只插入学号）
//                excelMapper.saveFourth(admissionInfos);
//                // 插入学位信息表（只插入学号）
//                excelMapper.saveFifth(admissionInfos);
//                // 插入学历信息表（只插入学号）
//                excelMapper.saveSixth(admissionInfos);
//                // 插入转递（邮寄信息表）
//                excelMapper.saveSeventh(admissionInfos);
//                // 档案信息表
//                excelMapper.saveEighth(archivalInfos);
                //往学生端插入学号数据
                // 创建两个列表来存储不同 flag 的对象
                excelMapper.saveFourteenth(admissionInfos);
                excelMapper.saveFifteenth(admissionInfos);
                List<AdmissionInfo> otherFlagList = new ArrayList<>();

                admissionInfos.forEach(admissionInfo -> otherFlagList.add(admissionInfo));

                excelMapper.saveTwelfth(otherFlagList);   //基本信息表
            }
        }catch (Exception e){

            e.printStackTrace();
            System.out.println(e.getMessage());
            //("数据异常，请联系管理员");
            sendMsg("数据异常，请联系管理员");
        }
    }


    private void sendMsg(List<String> msg) {
        try {
            //
            webSocketHandler.sendMsgList(msg);
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        }
    }
    private void sendMsg(String msg) {
        try {
            //
            webSocketHandler.sendMsg(msg);
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        }
    }




//录取信息表字段赋值
private List<AdmissionInfo> copyAdmissionInfos(List<EducationInfoVo> educationInfoVoList, String importType){
    List<AdmissionInfo> admissionInfos = educationInfoVoList.stream()
            .map(StudentInfoEntity -> {
                AdmissionInfo admissionInfo = new AdmissionInfo();
                admissionInfo.setOfficeId(StudentInfoEntity.getOfficeId());
                admissionInfo.setStudentId(StudentInfoEntity.getStudentId());
                admissionInfo.setRecordType("3"); //表示继续教育学院
                if(importType.equals("DBMS")){
                    admissionInfo.setApproveState(1);//审批状态待提交
                }else {
                    admissionInfo.setApproveState(3);//审批状态通过
                }
                admissionInfo.setTransferState(1);
                admissionInfo.setGradation(StudentInfoEntity.getLqcc());//层次
                admissionInfo.setYear(StudentInfoEntity.getLgnf()); //年度
                admissionInfo.setAdmissionMajor(StudentInfoEntity.getMajorName());//专业
                admissionInfo.setAdmissionNum(StudentInfoEntity.getZkzh());//准考证号
                admissionInfo.setName(StudentInfoEntity.getXm());//姓名
                admissionInfo.setGender(StudentInfoEntity.getXb());//性别
                // 将字符串转换为 Date 对象
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    if(StudentInfoEntity.getCsrq() != null){
                        Date birthDate = sdf.parse(StudentInfoEntity.getCsrq());
                        admissionInfo.setBirthday(birthDate);//出生日期
                    }
                } catch (ParseException e) {
                    System.out.println(e.getMessage());
                }
                admissionInfo.setPoliticalOutlook(StudentInfoEntity.getZzmm());//政治面貌
                admissionInfo.setNation(StudentInfoEntity.getMz());//民族
                admissionInfo.setIdCard(StudentInfoEntity.getSfzh());//身份证号
                // 设置录取学校为吉林师范大学
                admissionInfo.setAdmissionSchools("吉林师范大学");//录取学校
                admissionInfo.setAdmissionTime(StudentInfoEntity.getAdmissionDate());//录取时间
                admissionInfo.setEducationalSystem(StudentInfoEntity.getXz());//学制
                admissionInfo.setInfoSource("教务处招生数据");
                admissionInfo.setFlag(BsssStudentInfo.EDUCATION);
                return admissionInfo; // 返回生成的 AdmissionInfo 对象
            }).collect(Collectors.toList()); // 收集到 admissionInfos 列表中
    return admissionInfos;
}


    //毕业信息表字段赋值
    private List<NewGraduationInfo> copyGraduationInfos(List<EducationInfoVo> educationInfoVoList, String importType){
        List<NewGraduationInfo> graduationInfos = educationInfoVoList.stream()
                .map(StudentInfoEntity -> {

                    NewGraduationInfo newGraduationInfo = new NewGraduationInfo();
                    newGraduationInfo.setOfficeId(StudentInfoEntity.getOfficeId());
                    newGraduationInfo.setStudentId(StudentInfoEntity.getStudentId());

                    newGraduationInfo.setTransferState(1);
                    newGraduationInfo.setExamineeNum(StudentInfoEntity.getKsh());
                    newGraduationInfo.setAdmissionNum(StudentInfoEntity.getZkzh());//准考证号
                    newGraduationInfo.setName(StudentInfoEntity.getXm());
                    newGraduationInfo.setGender(StudentInfoEntity.getXb());

//                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
//                    try {
//                        Date birthday = dateFormat.parse(StudentInfoEntity.getCsrq());
//                        newGraduationInfo.setBirthday(birthday);
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }

                    newGraduationInfo.setPoliticalOutlook(StudentInfoEntity.getZzmm());
                    newGraduationInfo.setNation(StudentInfoEntity.getMz());
                    newGraduationInfo.setIdCard(StudentInfoEntity.getSfzh());
                    newGraduationInfo.setMajorName(StudentInfoEntity.getMajorName());
                    newGraduationInfo.setEducationalSystem(StudentInfoEntity.getXz());
                    newGraduationInfo.setGradation(StudentInfoEntity.getLqcc());
                    newGraduationInfo.setEnrollmentDate(StudentInfoEntity.getAdmissionDate());
                    newGraduationInfo.setYear(StudentInfoEntity.getLgnf());
                    newGraduationInfo.setTransferState(1);

                    return newGraduationInfo; // 返回生成的 AdmissionInfo 对象
                }).collect(Collectors.toList()); // 收集到 admissionInfos 列表中
        return graduationInfos;
    }

    //档案信息表字段赋值
    private List<ArchivalInfo> copyArchivalInfoInfos(List<EducationInfoVo> educationInfoVoList, String importType){
        List<ArchivalInfo> archivalInfos = educationInfoVoList.stream()
                .map(StudentInfoEntity -> {
                    ArchivalInfo archivalInfo = new ArchivalInfo();
                    archivalInfo.setName(StudentInfoEntity.getXm());
                    archivalInfo.setAdmissionMajor(StudentInfoEntity.getLqzy());
                    archivalInfo.setOfficeId(StudentInfoEntity.getOfficeId());
                    archivalInfo.setMajorName(StudentInfoEntity.getMajorName());
                    archivalInfo.setStudentId(StudentInfoEntity.getStudentId());
                    archivalInfo.setCandidateNumber(StudentInfoEntity.getKsh());
                    archivalInfo.setAdmissionTicketNumber(StudentInfoEntity.getZkzh());//准考证号
                    archivalInfo.setGender(StudentInfoEntity.getXb());
                    archivalInfo.setTransferState(1);
                    archivalInfo.setEthnicity(StudentInfoEntity.getMz());
                    archivalInfo.setGradation(StudentInfoEntity.getLqcc());
                    archivalInfo.setYear(StudentInfoEntity.getLgnf());
                    archivalInfo.setIdNumber(StudentInfoEntity.getSfzh());
                    archivalInfo.setTransferState(1);
                    return archivalInfo;
                }).collect(Collectors.toList());
        return archivalInfos;
    }

}
